"""ASR数据接收API
用于接收ASR服务推送的语音识别数据
"""

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import Optional
import logging
from datetime import datetime

logger = logging.getLogger(__name__)

class ASRData(BaseModel):
    """ASR数据模型"""
    start: int  # 开始时间戳
    end: int    # 结束时间戳
    text: str   # 识别的文本内容
    confidence: float  # 置信度
    keyframe: Optional[str] = None  # 关键帧信息

class ASRResponse(BaseModel):
    """ASR接收响应模型"""
    status: str
    message: str
    timestamp: str
    data_id: Optional[str] = None

# 如果这是独立的FastAPI应用
# app = FastAPI(title="ASR数据接收服务", description="接收ASR服务推送的语音识别数据")

# 如果要集成到现有的main.py中，请将以下路由添加到现有的app中

@app.post("/asr/data", response_model=ASRResponse)
async def receive_asr_data(asr_data: ASRData):
    """
    接收ASR服务推送的数据
    
    Args:
        asr_data: ASR识别数据，包含文本和关键帧信息
        
    Returns:
        ASRResponse: 处理结果
    """
    try:
        logger.info(f"收到ASR数据: {asr_data.text[:50]}...")
        
        # 数据验证
        if not asr_data.text or not asr_data.text.strip():
            raise HTTPException(status_code=400, detail="文本内容不能为空")
        
        if asr_data.confidence < 0 or asr_data.confidence > 1:
            raise HTTPException(status_code=400, detail="置信度必须在0-1之间")
        
        # 生成数据ID
        data_id = f"asr_{int(datetime.now().timestamp() * 1000)}"
        
        # 处理ASR数据
        processed_result = await process_asr_data(asr_data)
        
        logger.info(f"ASR数据处理完成，ID: {data_id}")
        
        return ASRResponse(
            status="success",
            message="ASR数据接收成功",
            timestamp=datetime.now().isoformat(),
            data_id=data_id
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"处理ASR数据失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"处理失败: {str(e)}")


async def process_asr_data(asr_data: ASRData) -> dict:
    """
    处理ASR数据的核心逻辑
    
    Args:
        asr_data: ASR数据
        
    Returns:
        dict: 处理结果
    """
    try:
        # 提取关键信息
        text_content = asr_data.text.strip()
        keyframe_info = asr_data.keyframe
        confidence = asr_data.confidence
        
        # 这里可以添加你的业务逻辑
        # 例如：
        # 1. 将文本内容存储到数据库
        # 2. 处理关键帧信息
        # 3. 触发后续的处理流程
        # 4. 与RAG系统集成，进行智能问答
        
        logger.info(f"处理文本: {text_content}")
        if keyframe_info:
            logger.info(f"处理关键帧: {keyframe_info}")
        
        # 示例：可以将文本发送给RAG系统进行处理
        # if hasattr(app.state, 'rag_engine'):
        #     rag_result = app.state.rag_engine.query(text_content)
        #     logger.info(f"RAG处理结果: {rag_result}")
        
        return {
            "text_length": len(text_content),
            "has_keyframe": keyframe_info is not None,
            "confidence": confidence,
            "processed_at": datetime.now().isoformat()
        }
        
    except Exception as e:
        logger.error(f"ASR数据处理失败: {str(e)}")
        raise


@app.get("/asr/health")
async def asr_health_check():
    """
    ASR服务健康检查
    """
    return {
        "status": "healthy",
        "service": "ASR数据接收服务",
        "timestamp": datetime.now().isoformat()
    }


# 批量接收ASR数据的接口（可选）
@app.post("/asr/batch", response_model=ASRResponse)
async def receive_asr_batch(asr_data_list: list[ASRData]):
    """
    批量接收ASR数据
    
    Args:
        asr_data_list: ASR数据列表
        
    Returns:
        ASRResponse: 批量处理结果
    """
    try:
        if not asr_data_list:
            raise HTTPException(status_code=400, detail="数据列表不能为空")
        
        if len(asr_data_list) > 100:  # 限制批量大小
            raise HTTPException(status_code=400, detail="批量数据不能超过100条")
        
        processed_count = 0
        failed_count = 0
        
        for asr_data in asr_data_list:
            try:
                await process_asr_data(asr_data)
                processed_count += 1
            except Exception as e:
                logger.error(f"处理单条ASR数据失败: {str(e)}")
                failed_count += 1
        
        batch_id = f"batch_{int(datetime.now().timestamp() * 1000)}"
        
        return ASRResponse(
            status="success" if failed_count == 0 else "partial_success",
            message=f"批量处理完成: 成功{processed_count}条, 失败{failed_count}条",
            timestamp=datetime.now().isoformat(),
            data_id=batch_id
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"批量处理ASR数据失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"批量处理失败: {str(e)}")